﻿namespace EyeOpen.BomberMan
{
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Drawing;

	public class Map : IEnumerable<ItemType>
	{
		private readonly ItemType[,] map;
		private readonly Action mapChanged;

		public Map(ItemType[,] map)
		{
			this.map = map;
			Size = new Size(map.GetUpperBound(0) + 1, map.GetUpperBound(1) + 1);
		}

		public Map(ItemType[,] map, Action mapChanged)
			: this(map)
		{
			this.mapChanged = mapChanged;
		}

		public Size Size { get; private set; }

		public ItemType this[int x, int y]
		{
			get
			{
				return map[x, y];
			}

			set
			{
				map[x, y] = value;

				if (mapChanged == null)
				{
					return;
				}

				if (value != ItemType.Bomb)
				{
					mapChanged();
				}
			}
		}

		public IEnumerator<ItemType> GetEnumerator()
		{
			return new MapEnumerator(this);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public Point GetPlayerPosition()
		{
			for (var y = 0; y < Size.Height; y++)
			{
				for (var x = 0; x < Size.Height; x++)
				{
					if (this[x, y] == ItemType.Player)
					{
						return new Point(x + 1, y + 1);
					}
				}
			}

			return new Point(-1, -1);
		}
	}
}